<template>
  <div class="picture-upload">
    <a-upload
      :custom-request="handleUpload"
      :show-upload-list="false"
      list-type="picture-card"
      class="avatar-uploader"
      :before-upload="beforeUpload"
    >
      <img v-if="props.picture.url" :src="props.picture.url" alt="avatar" />
      <div v-else>
        <loading-outlined v-if="loading"></loading-outlined>
        <plus-outlined v-else></plus-outlined>
        <div class="ant-upload-text">点击或者拖拽以上传图片</div>
      </div>
    </a-upload>
  </div>
</template>
<script setup>
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { PictureVO } from '@/common/PictureVO.js'
import { uploadPicture } from '@/api/picture.js'

const props = defineProps({
  picture: {
    type: Object,
    default: () => new PictureVO(),
    required: true,
  },
  onSuccess: {
    type: Object,
    default: () => new PictureVO(),
    required: true,
  },
})

const loading = ref(false)

const pictureUploadRequest = {
  id: '',
}
const handleUpload = async (file) => {
  loading.value = true

  try {
    let formdata = new FormData()
    formdata.append('file', file.file)

    if (props.picture?.value?.id > 0) {
      formdata.append('id', props.picture?.value?.id)
    }
    console.log('file:', file)
    const res = await uploadPicture(formdata)
    if (res.data.code === 0 && res.data.data) {
      console.log('上傳:', res.data.data)
      props.onSuccess?.(res.data.data)
      console.log('props.onSuccess::', props.onSuccess, props.picture)
      message.success('上传成功!')
    } else {
      message.error('错误:' + res.data.data)
    }
    loading.value = false
  } catch (e) {
    message.error(e.message)
  }
  loading.value = false
}
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('抱歉，目前仅支持jpg和png!')
  }
  const isLt6M = file.size / 1024 / 1024 < 6
  if (!isLt6M) {
    message.error('图片大小不能超过 6MB!')
  }
  return isJpgOrPng && isLt6M
}
</script>
<style scoped>
.picture-upload {
  width: 100%;
  height: 100%;
  text-align: center;
}

.picture-upload :deep(.ant-upload) {
  width: 100% !important;
  height: 100% !important;
  min-width: 152px;
  min-height: 152px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  font-size: 20px;
  font-family: 站酷快乐体2016修订版;
  color: #3d3232;
}

.picture-upload img {
  max-width: 100%;
  max-height: 480px;
}
</style>
